import { authMiddleware } from '@/lib/api';
import { cookies } from 'next/headers';
import { queryPath } from '@/services/api';
import QqPage from '@/app/[locale]/qq/qq';
import ResetPage from '@/app/[locale]/reset/reset';
import type { Metadata as MetadataNext } from 'next';
import { createError, getMetadata } from '@/lib/tool';
import { getTranslator } from 'next-intl/server';
import type { IPath } from '@/interfaces';
import { getTranslatedFields } from '@/lib/dictionaries';
import { notFound } from 'next/navigation';

export async function generateMetadata({
  params: { locale },
}: {
  params: {
    locale: string;
  };
}): Promise<MetadataNext> {
  const t = await getTranslator(locale);
  return getMetadata({ title: t('qqPage.qqAuthorization') });
}

async function getData(searchParams: { code: string; state: string }) {
  try {
    const token = authMiddleware(cookies());
    const req1 = queryPath({
      baseURL: process.env.APP_API_SERVER,
      token,
      query: {
        name: '/',
      },
    });

    const responses = await Promise.all([req1]);
    const resp1 = await ((await responses[0]) as Response).json();

    return {
      isSuccess: true,
      isError: false,
      data: {
        path: resp1.data as IPath,
        queryParams: searchParams,
      },
    };
  } catch (e: any) {
    return {
      isSuccess: false,
      isError: true,
      error: e,
    };
  }
}

export default async function Page({
  params: { locale },
  searchParams: { v, code, state },
}: {
  params: { locale: string };
  searchParams: {
    v?: 'h5';
    code: string;
    state: string;
  };
}) {
  if (!code || !state) {
    notFound();
  }

  const data = await getData({ code, state });
  if (data.isError) {
    return <ResetPage error={createError(data.error)} />;
  }

  const source = data.data!;
  const translatedFields = await getTranslatedFields(locale, 'qqPage');

  return <QqPage source={source} translatedFields={translatedFields} />;
}
